package moe.oil.db.api;

import lombok.Setter;
import moe.oil.db.service.FeedbackService;
import moe.oil.dto.feedback.FeedbackDTO;
import moe.oil.exception.feedback.FeedbackIdNotFoundException;
import moe.oil.exception.feedback.FeedbackIdNullException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * author: 紫月
 * Date: 2022/04/16 16:28
 * Description:
 *
 * @author - -
 */
@RestController
@RequestMapping("/feedback")
@Setter(onMethod_ = @Autowired)
@CrossOrigin
public class FeedbackController {

    private FeedbackService feedBackService;

    // 添加反馈信息
    @PostMapping
    public FeedbackDTO add(@Validated FeedbackDTO feedbackDTO) {
        return feedBackService.insertFeedback(feedbackDTO).get();
    }

    // 根据ID查询反馈信息
    @GetMapping("/{id}")
    public FeedbackDTO findAllById(@PathVariable("id") Long id) {
        return feedBackService.selectFeedbackById(id).orElseThrow(() -> new FeedbackIdNotFoundException(id)); //FeedBackIdNotFoundException
    }

    // 查询全部反馈信息
    @GetMapping("/{page}/{size}")
    public List<FeedbackDTO> findAll(@PathVariable("page") int page, @PathVariable("size")int size) {
        return feedBackService.selectAllFeedback(PageRequest.of(page, size));
    }

    // 删除反馈信息
    @DeleteMapping("/{id}")
    public int delete(@PathVariable("id") Long id) {
        return feedBackService.deleteFeedbackById(id);
    }

    // 更新反馈信息
    @PutMapping
    public FeedbackDTO update(@Validated FeedbackDTO feedbackDto) {
        if (feedbackDto.getFeedbackId() != null && feedbackDto.getFeedbackId() != 0) {
            return feedBackService.updateFeedback(feedbackDto).orElseThrow();
        } else {
            throw new FeedbackIdNullException();
        }
    }
}

